/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import entities.Question;
import entities.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Оксана
 */
public class QuestionDaoImpl extends AbstractDao implements QuestionDao {

    @Autowired
    public QuestionDaoImpl(JdbcTemplate jdbcTemplate) {
        super(jdbcTemplate);
    }
        
    @Override
    public void create(Question question) {
        jdbcTemplate.update("insert into questions (id, text, test) values (?, ?, ?)",
                question.getId(), question.getText(), question.getTest().getId());
    }

    @Override
    public Question findById(Integer id) {
        return jdbcTemplate.queryForObject("select id, text, test from questions "
                + "where id = ?", new Object[] {id}, new QuestionMapper());
    }

    @Override
    public List<Question> findByTestId(Integer testId) {
        return jdbcTemplate.query("select id, text, test from questions "
                + "where test = ?", new Object[] {testId}, new QuestionMapper());
    }
    
    private final static class QuestionMapper implements RowMapper<Question>{

        @Override
        public Question mapRow(ResultSet rs, int i) throws SQLException {
            Question question = new Question();
            question.setId(rs.getInt("id"));
            question.setText(rs.getString("text"));
            Test test = new Test();
            test.setId(rs.getInt("test"));
            question.setTest(test);
            return question;
        }
    }
}